var mongoose = require('mongoose');
var Schema = mongoose.Schema;

var util = require('util');

Port = new Schema({
	name : String,
	device : {
		type : Schema.ObjectId,
		ref : 'Device'
	},
	reference : {
		type : String,
		unique : true
	}
//	type : {
//		type : String,
//		enum : [ 'Boolean', 'Number' ]
//	},
//	direction : {
//		type : String,
//		enum : [ 'Input', 'Output' ]
//	},
//	description : String,
//	value : String
});

Port.index({
	device : 1,
	name : 1
}, {
	unique : true
});

Port.path('device').validate(function (v) {
  return typeof(v) != 'udefined' && v != null;
}, 'Device must be defined'); 

Port.pre('remove', function(next) {
	util.puts("Port pre-remove");
	var self = this;

	DeviceModel.findOne({
		_id : self.device
	}, function(e, device) {
		util.puts("  Found port parent device");
		device.ports.id(self._id).remove();
		util.puts("  Removed self from parent");
		device.save(next);
	});
});

Port.methods.add = function(callback) {
	var self = this;

	util.puts("Saving Port " + this._id + ", Parent: " + this.device);
	DeviceModel.findOne({
		_id : self.device
	}, function(e, device) {
		util.puts("  Parent Device " + device._id);
		device.ports.push(self._id);
		util.puts("Pushed");
		device.save();
	});

	callback = callback || function() {};
	this.save(callback);
};

PortModel = mongoose.model('Port', Port);
